package io.wins.vertx.web;

import java.util.Date;
import java.util.Set;

import com.google.common.net.HttpHeaders;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Router;
import io.wins.vertx.entity.Image;
import io.wins.vertx.utils.ImageHelper;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

public class AttachmentResource implements Resource {

    private Vertx vertx;
    private ServerProperties serverProperties;
    private static final Logger logger = LoggerFactory.getLogger(AttachmentResource.class);

    public static AttachmentResource create(final Vertx vertx, final ServerProperties serverProperties) {
        final AttachmentResource attachmentResource = new AttachmentResource();
        attachmentResource.vertx = vertx;
        attachmentResource.serverProperties = serverProperties;
        return attachmentResource;
    }

    @Override
    public Resource init(final Router router) {
        router.post("/api/file/upload").handler(ctx -> {
            final Set<FileUpload> uploads = ctx.fileUploads();
            final FileUpload fileUpload = (FileUpload) uploads.toArray()[0];
            ctx.response().setChunked(true);
            final Buffer fileBf = this.vertx.fileSystem().readFileBlocking(fileUpload.uploadedFileName());
            final BASE64Encoder encoder = new BASE64Encoder();
            final StringBuffer base64Data = new StringBuffer();
            base64Data.append("data:").append(fileUpload.contentType()).append(";base64,")
                .append(encoder.encode(fileBf.getBytes()));
            final Image image = new Image(new JsonObject());
            final String fileName = fileUpload.uploadedFileName();
            image.setImagePath(serverProperties.getUploadFilePath()+ fileName.substring(fileName.length() - 36));
            image.setImageBase(base64Data.toString());
            image.setCreatedOn(new Date().getTime());
            ImageHelper.create(this.vertx).SaveImage(image);
            ctx.response().setStatusCode(200)
                .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8)
                .end(image.toJson().toString());
        });
        router.get("/api/image/:id").handler(ctx -> {
            final String id = ctx.pathParam("id");
            if (StringUtils.isEmpty(id)) {
                ctx.response().setStatusCode(400).end();
            } else {
                ImageHelper.create(this.vertx).LoadImage(id, done -> {
                    if (done.succeeded()) {
                        final JsonObject result = (JsonObject) done.result().body().getList().get(0);
                        ctx.response().setStatusCode(200)
                            .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8)
                            .end(result.toString());
                    } else {
                        ctx.response().setStatusCode(400).end();
                    }
                });
            }
        });
        router.post("/api/image").handler(ctx -> {
            final JsonArray ids = ctx.getBodyAsJson().getJsonArray("imageIds");
            if (ids == null || ids.isEmpty()) {
                ctx.response().setStatusCode(400).end();
            } else {
                ImageHelper.create(this.vertx).ListImage(ids, done -> {
                    if (done.succeeded()) {
                        ctx.response().setStatusCode(200)
                            .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_CHARSET_UTF_8)
                            .end(done.result().body().getList().toString());
                    } else {
                        ctx.response().setStatusCode(400).end();
                    }
                });
            }
        });
        return this;
    }
}
